package com.taotao.slink.utils;

import cn.hutool.core.util.HashUtil;
import io.netty.util.internal.ThreadLocalRandom;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;

import java.util.Stack;

/**
 * <p>
 *
 * </p>
 *
 * @author fanbeibei
 * @version 1.0.0
 * @date 2023/6/26 15:00
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class SlinkUtils {

    /**
     * 创建短链接编码
     *
     * @param link
     * @return
     */
    public static String createShortLinkCode(String link) {
        if (null == link) {
            return null;
        }

        try {
            int hash = HashUtil.murmur32(link.getBytes("UTF-8"));
            if(hash < 0){
                hash = - hash;
            }
            return hex10To62((long) hash);
        } catch (Exception e) {

            log.error("", e);
            return null;
        }

    }


    /**
     * 解决hash碰撞
     *
     * @param linkCode
     * @return
     */
    public static String resolveHashCollision(String linkCode) {
        ThreadLocalRandom random = ThreadLocalRandom.current();
        return charSet[random.nextInt(62)] + linkCode + charSet[random.nextInt(62)];
    }


    private static final char[] charSet = "qwertyuiopasdfghjklzxcvbnm0123456789QWERTYUIOPASDFGHJKLZXCVBNM".toCharArray();

    /**
     * 10进制转62进制
     *
     * @param number
     * @return
     */
    @NotNull
    public static String hex10To62(Long number) {
        Long rest = number;
        Stack<Character> stack = new Stack<Character>();
        StringBuilder result = new StringBuilder(0);
        while (rest != 0 && rest >= 62) {
            stack.add(charSet[new Long((rest - (rest / 62) * 62)).intValue()]);
            rest = rest / 62;
        }

        if (rest > 0) {
            stack.add(charSet[new Long(rest).intValue()]);
        }

        for (; !stack.isEmpty(); ) {
            result.append(stack.pop());
        }
        return result.toString();
    }

    /**
     * 62进制转10进制
     *
     * @param sixty_str
     * @return
     */
    public static String hex62To10(String sixty_str) {
        Long dst = 0L;
        for (int i = 0; i < sixty_str.length(); i++) {
            char c = sixty_str.charAt(i);
            for (int j = 0; j < charSet.length; j++) {
                if (c == charSet[j]) {
                    dst = (dst * 62) + j;
                    break;
                }
            }
        }
        return dst.toString();
    }


}
